package com.lhc.controller;

import com.lhc.error.BusniessException;
import com.lhc.error.EmBussinessError;
import com.lhc.response.CommonReturnType;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

public class BaseController {
    public static final String CONTENT_TYPE_FORMED="application/x-www-form-urlencoded";


    //定义exception解决异常 避开tomcat层面的异常 出现异常后会进入 @ExceptionHandler 注解的方法
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Object handleException(HttpServletRequest request, Exception ex){
        Map<String,Object> map = new HashMap<>();
        if (ex instanceof BusniessException){
            BusniessException busniessException = (BusniessException)ex;
            map.put("errCode",busniessException.errorCode());
            map.put("errMsg",busniessException.errorMessage());
        }else {
            map.put("errCode", EmBussinessError.UNKNOWN_ERROR.errorCode());
            map.put("errMsg", EmBussinessError.UNKNOWN_ERROR.errorMessage());
        }
        return CommonReturnType.create(map,"fail");
    }
}
